package com.lcc.dingtalk.robot.service.message.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcc.dingtalk.robot.base.bean.ResultContext;
import com.lcc.dingtalk.robot.base.enums.ENMessageType;
import com.lcc.dingtalk.robot.mapper.AutoAnswerConfigMapper;
import com.lcc.dingtalk.robot.pojo.answer.AutoAnswerConfigPO;
import com.lcc.dingtalk.robot.service.message.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author lincc
 * @version 1.0 2020/7/27
 */
@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Resource
    private AutoAnswerConfigMapper autoAnswerConfigMapper;

    public static void main(String[] args) {
        String content = "银行明细是否存在:[AC110005,102,1,20200816]";
        String keyword = content.substring(0, content.indexOf(":"));
        String reqInfo = content.substring(content.indexOf("[") + 1, content.indexOf("]"));
        String params = "?entNum=%s&channelCode=%s&type=%s&date=%s";
        System.out.println(keyword);
        System.out.println(reqInfo);
        String[] arr = reqInfo.split(StrUtil.COMMA);
        System.out.println(String.format(params, arr));
    }


    public boolean canParseInt(String str) {
        //使用正则表达式判断该字符串是否为数字，第一个\是转义符，\d+表示匹配1个或 //多个连续数字，"+"和"*"类似，"*"表示0个或多个
        return str.matches("\\d+");
    }

    private AutoAnswerConfigPO getByKeyword(String keyword) {
        QueryWrapper<AutoAnswerConfigPO> queryWrapper = new QueryWrapper<>(new AutoAnswerConfigPO().setKeyword(keyword));
        List<AutoAnswerConfigPO> list = autoAnswerConfigMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            return null;
        } else if (list.size() == 1) {
            return list.get(0);
        } else {
            int random = (int) (Math.random() * list.size());
            return list.get(random);
        }
    }

    @Override
    public String autoAnswer(String content) {
        if (StrUtil.isBlank(content)) {
            return "???";
        }
        if (this.canParseInt(content)) {
            int reqInt = Integer.parseInt(content);
            if (reqInt<10){
                return String.valueOf(reqInt+1);
            }else{
                return "要不起";
            }
        }
        String keyword = content;
        if (content.contains("[") && content.contains("]")) {
            if (content.contains(":")) {
                keyword = content.substring(0, content.indexOf(":"));
            } else if (content.contains("：")) {
                keyword = content.substring(0, content.indexOf("："));
            } else {
                return "关键字分隔格式有误";
            }
        }
        AutoAnswerConfigPO autoAnswerConfig = this.getByKeyword(keyword);
        if (autoAnswerConfig == null) {
            return "暂时无法识别,你好好说话";
        } else if (ENMessageType.TEXT.getValue().equals(autoAnswerConfig.getType())) {
            return autoAnswerConfig.getReplyMessage();
        } else {
            String reqInfo = content.substring(content.indexOf("[") + 1, content.indexOf("]"));
            String[] arr = reqInfo.split(StrUtil.COMMA);
            String paramsStr = String.format(autoAnswerConfig.getParams(), arr);
            log.info("请求地址[{}]", autoAnswerConfig.getUrl());
            log.info("请求参数[{}]", paramsStr);
            try {
                String result = HttpRequest.post(autoAnswerConfig.getUrl() + paramsStr).execute().body();
                log.info("接口返回结果[{}]", result);
                ResultContext resultContext = JSONUtil.toBean(result, ResultContext.class);
                if (resultContext.getSuccess()) {
                    return resultContext.getInfo();
                } else {
                    return "接口返回有误" + resultContext.getInfo();
                }
            } catch (Exception e) {
                log.error("接口处理发生异常", e);
                return "接口处理发生异常";
            }
        }
    }

}
